package com.htx.zqs.blesmartmask.ui.callback;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.util.Log;
import android.widget.Toast;

import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.adapter.RvDeviceAdapter;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.Courses;
import com.htx.zqs.blesmartmask.listeners.GattListener;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.ThreadUtil;
import com.umeng.commonsdk.statistics.common.MLog;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;


/**
 * Created by zhao on 2018/5/22.
 */

public class MeBluetoothGattCallback extends BluetoothGattCallback {

    private Activity activity;
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private BluetoothGattCharacteristic bluetoothGattCharacteristicNotify;
    private BluetoothGattCharacteristic bluetoothGattCharacteristicData;
    private RvDeviceAdapter rvDeviceAdapter;
    private HashMap map;
    private OkhttpUtils bluetimeHttp;
    private int requestService = 0;

    @Override
    public void onConnectionStateChange(final BluetoothGatt gatt, int status, final int newState) {
        ThreadUtil.executeMainThread(new Runnable() {
            @Override
            public void run() {
                MyApplication.bluetoothGatt = gatt;
                if (newState == BluetoothGatt.STATE_CONNECTED || newState == BluetoothGatt.STATE_CONNECTING) {
//                    if (activity != null) {

                    Toast.makeText(activity, activity.getResources().getString(R.string.bluetooth_connect_success), Toast.LENGTH_SHORT).show();
//                    }
                    requestService =  (int)SPUtil.get(activity, gatt.getDevice().getAddress(), 0, "requestService");
                    MyApplication.isConnected = true;
                    BlEUtile.getmKProgressHUD(activity).dismiss();
                    //连接成功后就去找出该设备中的服务
                    gatt.discoverServices();
                } else if (newState == BluetoothGatt.STATE_DISCONNECTED || newState == BluetoothGatt.STATE_DISCONNECTING) {
                    if (activity != null) {
                        Toast.makeText(activity, activity.getResources().getString(R.string.bluetooth_disconnect), Toast.LENGTH_SHORT).show();
                    }
                    MyApplication.isConnected = false;
                    if (activity != null) {
                        BlEUtile.getmKProgressHUD(activity).dismiss();
                    }
                    MyApplication.limitSeconds = 0;
                    MyApplication.bluetoothGatt = null;
                    gatt.close();
                } else {
                    Log.e("new", "run: " + newState);
                }
                rvDeviceAdapter.notifyDataSetChanged();
            }
        });
    }

//    @Override //当向设备Descriptor中写数据时，会回调该函数
//    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
//        MyApplication.bluetoothGatt = gatt;
//        System.out.println("onDescriptorWriteonDescriptorWrite = " + status + ", descriptor =" + descriptor.getUuid().toString());
//        ThreadUtil.executeMainThread(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(activity, "写入特征", Toast.LENGTH_SHORT).show();
//            }
//        });
//    }

    @Override
    public void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
        //   Log.e("gatt", "onServicesDiscovered: " + 222);
        ThreadUtil.executeMainThread(new Runnable() {
            @Override
            public void run() {
                byte[] buffer = characteristic.getValue();
                String string = new String(buffer);
                int[] intArray = new int[buffer.length];
                for (int i = 0; i < intArray.length; i++) {
                    intArray[i] = (buffer[i] & 0xff);
                }
                //验证
                if (string.startsWith("ATN")) {
                    MyApplication.bluetoothState = Contants.STATE_NO_RUN;
                }
                //油水
                //   Log.e("gatt", "onServicesDiscovered: " + 333);
                if (string.startsWith("AT-C")) {
                    //  Log.e("gatt", "onServicesDiscovered: " + 444);
                    MyApplication.bluetoothState = Contants.STATE_NO_RUN;
                    //       Log.e("gatt", "onServicesDiscovered: " + 555);
                    if (gattListener != null) {
                        gattListener.setWaterData(gatt, characteristic);
                    }
                }
                //面膜
                if (string.startsWith("ATJ")) {
                    //   Log.e("gatt", "onServicesDiscovered: " + "mianmo");
                    int state = intArray[11];
                    MyApplication.state = state;
                    int index = intArray[4] * 256 * 256 + intArray[5] * 256 + intArray[6];
                    if (state != 0) {
                        MyApplication.runningIndex = index;
                    } else {
                        MyApplication.runningIndex = 100000;
                    }
                    if (state == 1) {
                        MyApplication.limitSeconds++;
                        requestService++;
                        SPUtil.put(activity, gatt.getDevice().getAddress(), MyApplication.limitSeconds, "limitSeconds");


                        Log.e("======" + requestService, "==137==" + MyApplication.limitSeconds);
                        if (BlEUtile.isNetworkConnected(activity)) {
                            map = new HashMap();
                             Log.e("======"+requestService,"==140==");
                            if (requestService % 60 == 0) {
                                Log.e("======" + string, "==142==");
                                if (bluetimeHttp == null) {
                                    bluetimeHttp = new OkhttpUtils(activity, Contants.BLUE_TIME, new OkListener() {
                                        @Override
                                        public void onSuccess(int requestCode, String string) {
                                            Log.e("======" + string, "==143==");
                                            requestService = 0;
                                            SPUtil.clear(activity,"requestService");
                                        }

                                        @Override
                                        public void onError(int requestCode, IOException e) {
                                            Log.e("======" + e, "==150==");
                                            SPUtil.put(activity, gatt.getDevice().getAddress(), requestService, "requestService");
                                        }
                                    });
                                }
                                map.clear();
                                map.put("address", gatt.getDevice().getAddress());
                             //   map.put("numberlong", MyApplication.limitCount);
                                map.put("min", requestService);
                            //    bluetimeHttp.postForm(Contants.BLUE_TIME,Contants.BASE_URL+"bluetimeallequals.link",map);
                                bluetimeHttp.postForm(Contants.BLUE_TIME,Contants.BASE_URL+"bluetimeallequals.link",map);
                            }
                        }else {
                            SPUtil.put(activity, gatt.getDevice().getAddress(), requestService, "requestService");
                        }
                    }
                    if (gattListener != null) {
                        gattListener.setCourseData(gatt, characteristic);
                    }
                }
            }
        });
    }

    private GattListener gattListener;

    public void setOnListener(GattListener gattListener) {
        this.gattListener = gattListener;
    }

    /**
     * @param gatt
     * @param status //当设备是否找到服务时，会回调该函数
     */
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        MyApplication.bluetoothGatt = gatt;
        if (status == BluetoothGatt.GATT_SUCCESS) {//找到服务了
            if (bluetoothGattCharacteristicNotify == null) {
                BluetoothGattService bluetoothGattService = gatt.getService(Contants.SERVICE_UUID);
                bluetoothGattCharacteristicNotify = bluetoothGattService.getCharacteristic(Contants.CHARACTERISTIC_NOTIFY_UUID);

            }
            if (bluetoothGattCharacteristicData == null) {
                BluetoothGattService bluetoothGattService = gatt.getService(Contants.SERVICE_UUID);
                bluetoothGattCharacteristicData = bluetoothGattService.getCharacteristic(Contants.CHARACTERISTIC_DATA_UUID);
            }
            boolean isEnableNotification = gatt.setCharacteristicNotification(bluetoothGattCharacteristicNotify, true);
            if (isEnableNotification) {
                List<BluetoothGattDescriptor> descriptorList = bluetoothGattCharacteristicNotify.getDescriptors();
                if (descriptorList != null && descriptorList.size() > 0) {
                    for (BluetoothGattDescriptor descriptor : descriptorList) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        gatt.writeDescriptor(descriptor);
                    }
                }
            }
        }
    }

private boolean isNeedNetData ;
    public boolean testStart(int time) {
        //  MyApplication.bluetoothGatt.discoverServices();
        if (MyApplication.bluetoothGatt != null && bluetoothGattCharacteristicData != null) {
            byte[] buff = new byte[10];
            int[] intArray = {0x41, 0x54, 0x2d, 0x50, 0xc2, 0x83, 0x83, time, 0x0d, 0x0a};
            byte[] data = {0x41, 0x54, 0x2d, 0x50, (byte) 0xc2, (byte) 0x83, (byte) 0x83, 0x06, 0x0d, 0x0a};
            for (int i = 0; i < intArray.length; i++) {
                buff[i] = (byte) (intArray[i] & 0xff);
            }
            bluetoothGattCharacteristicData.setValue(buff);
            boolean writeSuccess = MyApplication.bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristicData);
            if (writeSuccess) {
                Log.v("MaskState", "发送成功");
              //    Toast.makeText(activity, "油水测试数据发送成功", Toast.LENGTH_SHORT).show();
                MyApplication.isTestWater = true;
                isNeedNetData = true ;
                SPUtil.put(activity,"isNeedNetData",isNeedNetData,"isNeedNetData");
                return true;
            } else {
                Toast.makeText(activity, activity.getResources().getString(R.string.fail_test_water), Toast.LENGTH_SHORT).show();
              //  Log.v("MaskState", "发送失败");
                return false;
            }
        } else {
            return false;
        }
    }

    public boolean testSpecial() {
        if (MyApplication.bluetoothGatt != null && bluetoothGattCharacteristicData != null) {
            int[] intArray = {0x41, 0x54, 0x2d, 0x53, 01, 03, 0x0f, 05, 01, 0x0d, 0x0a};
            byte[] buff = new byte[intArray.length];

            intArray[4] = 01;
            intArray[5] = 14;
            intArray[6] = 05;
            intArray[7] = 01;
            intArray[8] = 01;

            for (int i = 0; i < intArray.length; i++) {
                buff[i] = (byte) (intArray[i] & 0xff);
            }
            bluetoothGattCharacteristicData.setValue(buff);
            boolean writeSuccess = MyApplication.bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristicData);
            if (writeSuccess) {
                Toast.makeText(activity, intArray[4] + "-" + intArray[5] + "-" + intArray[6] + "-" + intArray[7] + "-" + intArray[8], Toast.LENGTH_LONG).show();
                Log.e("test", "onServicesDiscovered: 我到了这里  ");
                return true;

            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public boolean powerOff() {
        if (MyApplication.bluetoothGatt != null && bluetoothGattCharacteristicData != null) {
            byte[] buff = new byte[10];
            int[] intArray = {0x41, 0x54, 0x2d, 0x4d, 0x0d, 0x0a};
            for (int i = 0; i < intArray.length; i++) {
                buff[i] = (byte) (intArray[i] & 0xff);
            }
            bluetoothGattCharacteristicData.setValue(buff);
            boolean writeSuccess = MyApplication.bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristicData);
            if (writeSuccess) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public boolean waterStart(Courses course, int level) {
    Log.e("=====282","===");
        if (MyApplication.bluetoothGatt != null && bluetoothGattCharacteristicData != null && course != null) {
            int[] intArray = {0x41, 0x54, 0x2d, 0x51,
                    194, 131, 131, 0x00,
                    0x00, 0x00, 0x00, 0x00,
                    0x00,
                    0x00, 0x00, 0x00};

            int frequency = course.getFrequency();
            int percentage = course.getPercentage();
            if (frequency < 40) {
                frequency = 40;
            }
            if (frequency > 16000) {
                frequency = 16000;
            }
            if (frequency < 500) {
                int i = (int) (10000 / (frequency * 1.536));
                if (i > 255) {
                    i = 255;
                }
                intArray[4] = i;

                i = (int) (i * (percentage / 100.0));
                intArray[5] = i;
                intArray[6] = 0xee;

            } else {
                int x = 0;
                if (frequency < 1000) {
                    x = 5;
                } else if (frequency <= 2000) {
                    x = 4;
                } else if (frequency <= 4000) {
                    x = 3;
                } else if (frequency <= 8000) {
                    x = 2;
                } else {
                    x = 1;
                }

                int L = (int) (256 - 8000000 / (frequency * Math.pow(2, x + 1)));
                if (L < 1) {
                    L = 1;
                }
                if (L > 0xfe) {
                    L = 0xfe;
                }

                if (percentage < 5) {
                    percentage = 5;
                }
                if (percentage > 95) {
                    percentage = 95;
                }
                percentage = 100 - percentage;
                int H = (int) (256 - percentage * (256 - L) / 100.0);
                intArray[4] = H;
                intArray[5] = L;
                intArray[6] = x + 0x80;
            }
            Log.e("==========blue==385===="+course.getName(),"==============="+intArray[4]);
            Log.e("==========blue==385===="+course.getName(),"==============="+intArray[5]);
            Log.e("==========blue==385===="+course.getName(),"==============="+intArray[6]);

            int time0 = course.getTimeone();
            int time1 = course.getTimetwo();
            int time2 = course.getTimethree();

            if (time0 + time1 + time2 < 20) {
                intArray[8] = time0;
                intArray[7] = 20 - time0;
                intArray[12] = 20 - time0 - time1;
            } else {
                intArray[8] = time0;
                intArray[7] = time1 + time2;
                intArray[12] = time2;
            }
            Log.e("==========blue==385===="+course.getName(),"==============="+intArray[7]);
            Log.e("==========blue==385===="+course.getName(),"==============="+intArray[8]);
            Log.e("==========blue==385===="+course.getName(),"==============="+intArray[12]);

            int index = course.getId();
            intArray[9] = (int) (index / 256.0 / 256.0);
            intArray[10] = (int) (index % (256 * 256) / 256.0);
            intArray[11] = index % 256;
            Log.e("==========blue==385===="+course.getName(),"==============="+intArray[9]);
            Log.e("==========blue==385===="+course.getName(),"==============="+intArray[10]);
            Log.e("==========blue==385===="+course.getName(),"==============="+intArray[11]);

            int p = 100 - (level * 50);
//            if (level == 0) {
//                p = 97;
//            } else if (level == 1) {
//                p = 64;
//            } else if (level == 2) {
//                p = 0;
//            }

                p = 100 - level;


            p = (int) (256 - (256 - 131) * p / 100.0);
            if (p > 255) {
                p = 255;
            }
            if (p < 0) {
                p = 0;
            }

            intArray[13] = p;
            intArray[14] = p;
            intArray[15] = p;
            Log.e("384", "waterStart: "+intArray );
            Log.e("==========blue==385===="+course.getName(),"==============="+p);

            byte[] buff = new byte[intArray.length];
            for (int i = 0; i < intArray.length; i++) {
                buff[i] = (byte) (intArray[i] & 0xff);
            }

            bluetoothGattCharacteristicData.setValue(buff);
            boolean writeSuccess = MyApplication.bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristicData);
            if (writeSuccess) {

                return true;
            } else {
                Log.v("MaskState", "发送失败");
                return false;
            }
        } else {
            return false;
        }
    }


    public boolean stopCourse() {
        if (MyApplication.bluetoothGatt != null && bluetoothGattCharacteristicData != null) {
            int[] intArray = {0x41, 0x54, 0x2d, 0x52, 0x00, 0x0d, 0x0a};
            byte[] buff = new byte[intArray.length];
            for (int i = 0; i < intArray.length; i++) {
                buff[i] = (byte) (intArray[i] & 0xff);
            }
            bluetoothGattCharacteristicData.setValue(buff);
            boolean writeSuccess = MyApplication.bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristicData);
            if (writeSuccess) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public boolean pauseCourse() {
        if (MyApplication.bluetoothGatt != null && bluetoothGattCharacteristicData != null) {
            int[] intArray = {0x41, 0x54, 0x2d, 0x52, 0xff, 0x0d, 0x0a};
            byte[] buff = new byte[intArray.length];
            for (int i = 0; i < intArray.length; i++) {
                buff[i] = (byte) (intArray[i] & 0xff);
            }
            bluetoothGattCharacteristicData.setValue(buff);
            boolean writeSuccess = MyApplication.bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristicData);
            if (writeSuccess) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public boolean continueCourse() {
        if (MyApplication.bluetoothGatt != null && bluetoothGattCharacteristicData != null) {
            int[] intArray = {0x41, 0x54, 0x2d, 0x52, 0x01, 0x0d, 0x0a};
            byte[] buff = new byte[intArray.length];
            for (int i = 0; i < intArray.length; i++) {
                buff[i] = (byte) (intArray[i] & 0xff);
            }
            bluetoothGattCharacteristicData.setValue(buff);
            boolean writeSuccess = MyApplication.bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristicData);
            if (writeSuccess) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
    public boolean changVoltage(int level) {
        if (MyApplication.bluetoothGatt != null && bluetoothGattCharacteristicData != null) {
            int[] intArray = {0x41, 0x54, 0x2d, 0x56, 0x01, 0x0d, 0x0a};

            int p;
            p = 100 - level;
            p = (int) (256 - (256 - 131) * p / 100.0);
            if (p > 255) {
                p = 255;
            }
            if (p < 0) {
                p = 0;
            }
            intArray[4] = p;
            byte[] buff = new byte[intArray.length];
            for (int i = 0; i < intArray.length; i++) {
                buff[i] = (byte) (intArray[i] & 0xff);
            }
            bluetoothGattCharacteristicData.setValue(buff);
            boolean writeSuccess = MyApplication.bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristicData);
            if (writeSuccess) {

                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }


    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    public void setAdapter(RvDeviceAdapter rvDeviceAdapter) {
        this.rvDeviceAdapter = rvDeviceAdapter;
    }
}
